package utils;

import play.Logger;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class SecureUtils {
	public static Long secureTimeoutMills = 1000L;
	
	private static char hexDigits[] = {
			'0',
			'1',
			'2',
			'3',
			'4',
			'5',
			'6',
			'7',
			'8',
			'9',
			'a',
			'b',
			'c',
			'd',
			'e',
			'f'
	};

	public static Long generateTimeMillis(){
		return System.currentTimeMillis();
	}
	
	public static Long generateRandomUniqueId(){
		Long currentMillis = System.currentTimeMillis();
		
		Random random = new Random();
		Long currentRandom = random.nextLong();

        Long randomNumber = currentMillis + currentRandom;
		return randomNumber;
	}
	
	public static String generateMD5String(String src){
		byte[] srcByte = src.getBytes();
		StringBuilder finalMD5 = new StringBuilder();
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(srcByte);
			byte generatedMD5Byte[] = messageDigest.digest();
			
			for(byte curByte: generatedMD5Byte){
				finalMD5.append(hexDigits[curByte >>> 4 & 0xf]);
				finalMD5.append(hexDigits[curByte & 0xf]);
			}
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return finalMD5.toString();
	}

    public static String generateHMACString(String key, String message){
        SecretKey secretkey = new SecretKeySpec(key.getBytes(), "HmacMD5");
        try {
            Mac mac = Mac.getInstance(secretkey.getAlgorithm());
            mac.init(secretkey);
            byte[] hmac = mac.doFinal(message.getBytes());

            int length = hmac.length;
            char[] result = new char[length * 2];
            int k = 0;
            for(int i = 0; i < length; i++){
                byte byte0 = hmac[i];
                result[k++] = hexDigits[byte0 >>> 4 & 0xf];
                result[k++] = hexDigits[byte0 & 0xf];
            }
            return String.valueOf(result);
        } catch (Exception e) {
            Logger.error(e.getMessage());
            return null;
        }
    }
}
